/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package UserBN;

import entity.SwhUser;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Mr-Quick
 */
public class Authentication {

    private HttpSession session;
    private static Authentication instance;

    public static Authentication getInstance() {
        if (instance == null) {
            instance = new Authentication();
        }
        return instance;
    }

    public HttpSession getSession() {
        return session;
    }

    public void setSession(HttpSession session) {
        this.session = session;
    }
    EntityManager em;

    private Authentication() {
        String persistenceUnitName = "SweetHomePU";
        EntityManagerFactory factory = Persistence.createEntityManagerFactory(persistenceUnitName);
        em = factory.createEntityManager();
    }

    public String getUsername() {

        if (session != null) {
            if(session.getAttribute("username") != null){
                return session.getAttribute("username").toString();
            }
        }
        return null;

    }

    public String login(String username, String password) {
        try {
            UserService us = new UserService();
            SwhUser user = us.findAccountByUsername(username);
            if (user != null) {
                if (user.getPassword().equals(password)) {
                    session.setAttribute("username", username);
                    return "true";
                }
                else
                {
                    return "false";
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public String logout() {
        try {
            session.removeAttribute("username");
            return "true";
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}